import pygame
import sys
from src.core.sprite import Sprite
from src.core.inventory import Inventory
from src.core.storage import Storage
from src.scenes.login_scene import LoginScene
from src.scenes.map_scene import MapScene
from src.scenes.battle import BattleSystem
from src.system.save_system import SaveSystem
from src.system.config import *


# 初始化Pygame
pygame.init()
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption(GAME_TITLE)

# 创建游戏场景和系统
storage = Storage(WINDOW_WIDTH, WINDOW_HEIGHT)
map_scene = MapScene(WINDOW_WIDTH, WINDOW_HEIGHT)

# 创建精灵
player_sprite = Sprite(**PLAYER_ATTR)
enemy_sprite = Sprite(**ENEMY_ATTR)
player_sprite.load_image(IMAGE_PATHS["player"])
enemy_sprite.load_image(IMAGE_PATHS["enemy"])

# 创建战斗系统
battle_system = BattleSystem(player_sprite, enemy_sprite)

# 创建背包和仓库
inventory = Inventory(WINDOW_WIDTH, WINDOW_HEIGHT)
storage = Storage(WINDOW_WIDTH, WINDOW_HEIGHT)
inventory.add_sprite(player_sprite)

# 创建字体对象
font = pygame.font.Font(None, 36)

def draw_hp_text(screen, sprite, x, y):
    # 使用int()去掉小数部分
    hp_text = f"HP: {int(sprite.current_hp)}/{int(sprite.max_hp)}"
    text_surface = font.render(hp_text, True, BLACK)
    screen.blit(text_surface, (x, y))

# 在main函数开始处添加
def main():
    pygame.init()
    screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption(GAME_TITLE)
    
    # 创建登录场景
    login_scene = LoginScene(WINDOW_WIDTH, WINDOW_HEIGHT)
    current_scene = "login"
    current_enemy_index = None
    save_system = SaveSystem()
    
    # 游戏主循环
    clock = pygame.time.Clock()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break

            # 登录场景事件处理
            if current_scene == "login":
                result = login_scene.handle_event(event)
                if result:
                    success, game_data = result
                    if success:
                        current_scene = SCENE_MAP
                        save_system.set_username(login_scene.username_text)  # 在这里设置用户名
                        if game_data:
                            player_sprite.current_hp = game_data.get('current_hp', player_sprite.max_hp)
                            
                            # 加载背包数据
                            inventory.clear()
                            for sprite_data in game_data.get('inventory', []):
                                sprite = Sprite(sprite_data['name'], 
                                            sprite_data['max_hp'],
                                            sprite_data['attack'],
                                            sprite_data['defense'],
                                            sprite_data['speed'])
                                sprite.load_image(IMAGE_PATHS["enemy"])
                                inventory.add_sprite(sprite)
                            
                            # 加载仓库数据（精灵蛋）
                            storage.clear()
                            for egg_data in game_data.get('eggs', []):  # 改用eggs字段
                                sprite = Sprite(egg_data['name'],
                                           egg_data['max_hp'],
                                           egg_data['attack'],
                                           egg_data['defense'],
                                           egg_data['speed'])
                                storage.add_egg(sprite)
                                if egg_data.get('hatch_time'):  # 如果有孵化时间，说明已经开始孵化
                                    storage.start_hatching(sprite, egg_data['hatch_time'])
                           
            
            # 游戏场景事件处理
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if current_scene == SCENE_BATTLE:
                    if battle_system.handle_click(event.pos):
                        if battle_system.battle_result == "VICTORY":
                            storage.add_egg(enemy_sprite)
                        current_scene = SCENE_MAP
                        battle_system.battle_ended = False
                        battle_system.battle_result = ""
                        player_sprite.current_hp = player_sprite.max_hp
                        enemy_sprite.current_hp = enemy_sprite.max_hp
                        if current_enemy_index is not None:
                            map_scene.remove_sprite(current_enemy_index)
                            current_enemy_index = None
                
                elif current_scene == SCENE_STORAGE:
                    if storage.handle_click(event.pos):
                        pass
                    elif map_scene.handle_back_click(event.pos):
                        current_scene = SCENE_MAP
                
                elif current_scene == SCENE_INVENTORY:
                    inventory.handle_click(event.pos)
                    if map_scene.handle_back_click(event.pos):
                        current_scene = SCENE_MAP
                
                elif current_scene == SCENE_MAP:
                    if map_scene.handle_storage_click(event.pos):
                        current_scene = SCENE_STORAGE
                    elif map_scene.handle_inventory_click(event.pos):
                        current_scene = SCENE_INVENTORY

        # 游戏逻辑更新
        if current_scene == SCENE_MAP:
            map_scene.handle_input()
            collision_index = map_scene.check_battle_collision()
            if collision_index is not None:
                current_scene = SCENE_BATTLE
                current_enemy_index = collision_index
                enemy_sprite.current_hp = enemy_sprite.max_hp

        if current_scene == SCENE_STORAGE:
            hatched_sprites = storage.check_hatched_eggs()
            for sprite in hatched_sprites:
                new_sprite = Sprite(sprite.name, sprite.max_hp, 
                                sprite.attack, sprite.defense, sprite.speed)
                new_sprite.load_image(IMAGE_PATHS["enemy"])
                inventory.add_sprite(new_sprite)
                success_text = font.render("HATCH SUCCESS!", True, (0, 255, 0))
                screen.blit(success_text, (WINDOW_WIDTH//2 - success_text.get_width()//2, 50))
                pygame.display.flip()
                pygame.time.wait(1000)

        # 在场景绘制之前添加自动保存逻辑
        if current_scene != "login" and save_system.should_save():
            save_system.save_game(player_sprite, inventory, storage)
            
        # 场景绘制
        screen.fill(WHITE)
        if current_scene == "login":
            login_scene.draw(screen)
        elif current_scene == SCENE_MAP:
            map_scene.draw(screen)
        elif current_scene == SCENE_STORAGE:
            storage.draw(screen)
            map_scene.draw_back_button(screen)
        elif current_scene == SCENE_INVENTORY:
            inventory.draw(screen)
            map_scene.draw_back_button(screen)
        elif current_scene == SCENE_BATTLE:
            battle_system.draw(screen)
            draw_hp_text(screen, player_sprite, 100, 120)
            draw_hp_text(screen, enemy_sprite, 600, 120)
        
        pygame.display.flip()
        clock.tick(60)
    
    # 游戏退出
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()